package com.project.springboot.service.file.impl;

import com.gitee.yongzhuzl.commonutil.util.random.RandomUtil;
import com.project.springboot.service.file.FileService;
import com.project.springboot.utils.ZipUtil;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * description: 文件相关服务接口实现类
 * @author 朱正磊
 * @date 2023-12-18 10:17:30
 */
@Service("fileService")
public class FileServiceImpl implements FileService {

    /**
     * description: 下载文件到服务器
     * @author 朱正磊
     * @date 2023-12-18 13:35:13
     * @param fileUrl 文件下载的URL地址
     * @param fileDir 文件保存的目录
     * @param extension 生成文件的扩展名
     */
    @Override
    public void downloadFileToServer(String fileUrl, String fileDir, String extension) {
        try {
            // 创建URL对象并打开连接
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方式为GET
            connection.setRequestMethod(HttpMethod.GET.name());
            // 获取响应码
            int responseCode = connection.getResponseCode();
            // 如果响应码为200，表示请求成功
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 获取输入流
                InputStream inputStream = connection.getInputStream();
                // 创建输出流
                String filePath = fileDir + RandomUtil.getUuidNoLine() + extension;
                FileOutputStream outputStream = new FileOutputStream(filePath);
                // 创建缓冲区
                byte[] buffer = new byte[2048];
                int bytesRead;
                // 将输入流保存到输出流中
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                // 关闭输入流和输出流
                outputStream.close();
                inputStream.close();
            }
            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * description: 下载文件到客户端
     * @author 朱正磊
     * @date 2023-12-18 13:55:56
     * @param file 文件
     * @return 返回HTTP响应对象
     */
    @Override
    public ResponseEntity<FileSystemResource> downloadFileToClient(File file) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + file.getName());
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }

    /**
     * description: 下载zip压缩文件到客户端
     * @author 朱正磊
     * @date 2023-12-18 14:55:22
     * @param zipPathDir zip压缩文件目录
     * @param zipFileName zip压缩文件名称
     * @param fileList 待压缩文件全路径集合
     * @return 返回HTTP响应对象
     */
    @Override
    public ResponseEntity<FileSystemResource> downloadZipToClient(String zipPathDir, String zipFileName, List<String> fileList) {
        ZipUtil.compressFiles(zipPathDir, zipFileName, fileList);
        String filePath = zipPathDir + zipFileName;
        return downloadFileToClient(new File(filePath));
    }

}
